<template>
  <el-container class="layout">
    <el-header class="topbar">
      <div class="brand">数据统计</div>
      <div class="spacer"></div>
      <div class="user-info" ref="userAreaRef">
        <span class="gray-text">招聘数据</span>
        <span class="gray-text">我的客服</span>
        <span class="gray-text">账号权益</span>
        <span class="gray-text">升级VIP</span>
        <span
          class="user-name"
          :class="{ active: showUserCard }"
          @click="toggleUserCard"
        >
          {{ user.name || user.phone || '用户' }}
        </span>
        <el-avatar
          :size="36"
          :src="user.avatar || defaultAvatar"
          @click="toggleUserCard"
          style="cursor: pointer;"
        />

        <div v-if="showUserCard" class="user-card" ref="userCardRef">
          <div class="user-card-header">
            <el-avatar :size="44" :src="user.avatar || defaultAvatar" />
            <div class="uc-head">
              <div class="uc-name">{{ user.name || user.phone || '用户' }}</div>
              <div class="uc-pos">{{ user.position || user.email || '—' }}</div>
            </div>
          </div>
          <div class="user-card-body">
            <div class="uc-item" @click="goAccount">账号设置</div>
            <div class="uc-item" @click="goSecurity">安全设置</div>
          </div>
          <div class="user-card-footer">
            <div class="uc-logout" @click="logout">退出登录</div>
          </div>
        </div>
      </div>
    </el-header>
    <el-container>
      <el-aside width="200px" class="sidebar">
        <el-menu
          default-active="stats"
          class="el-menu-vertical-demo"
          @select="handleMenuSelect"
        >
          <el-menu-item index="jobs">职位管理</el-menu-item>
          <el-menu-item index="recommend">推荐牛人</el-menu-item>
          <el-menu-item index="search">搜索牛人</el-menu-item>
          <el-menu-item index="chat">沟通</el-menu-item>
          <el-menu-item index="intention">意向沟通</el-menu-item>
          <el-menu-item index="interact">互动</el-menu-item>
          <el-menu-item index="talent">牛人管理</el-menu-item>
          <el-menu-item index="props">道具</el-menu-item>
          <el-menu-item index="tools">工具箱</el-menu-item>
          <el-menu-item index="stats">数据统计</el-menu-item>
          <el-menu-item index="more">更多</el-menu-item>
        </el-menu>
      </el-aside>
      <el-main class="content">
        <div class="query-section">
          <el-card class="query-card">
            <div class="query-form">
              <div class="form-item">
                <label>统计周期：</label>
                <el-radio-group v-model="queryParams.period" @change="handlePeriodChange">
                  <el-radio :value="1">日统计</el-radio>
                  <el-radio :value="2">周统计</el-radio>
                  <el-radio :value="3">月统计</el-radio>
                </el-radio-group>
              </div>
              <div class="form-item">
                <label>统计日期：</label>
                <el-date-picker
                  v-model="queryParams.stats_date"
                  :type="datePickerType"
                  :format="dateFormat"
                  value-format="YYYY-MM-DD"
                  placeholder="选择日期"
                  @change="handleDateChange"
                />
              </div>
              <div class="form-item">
                <label>统计类型：</label>
                <el-radio-group v-model="queryParams.stats_type">
                  <el-radio :value="0">全部</el-radio>
                  <el-radio :value="1">业务指标</el-radio>
                  <el-radio :value="2">合规指标</el-radio>
                  <el-radio :value="3">互动指标</el-radio>
                </el-radio-group>
              </div>
              <div class="form-actions">
                <el-button type="primary" @click="handleQuery" :loading="loading">
                  查询
                </el-button>
                <el-button @click="handleReset">重置</el-button>
              </div>
            </div>
          </el-card>
        </div>

        <div class="stats-section" v-if="statsData">
          <el-card class="stats-card">
            <template #header>
              <div class="card-header">
                {{ statsData.period_name }}（{{ statsData.stats_date }}）
              </div>
            </template>

            <!-- 业务指标 -->
            <div v-if="showBusinessStats" class="stats-block">
              <h3 class="stats-title">业务指标</h3>
              <div class="stats-grid">
                <div
                  v-for="(value, key) in filteredBusinessData"
                  :key="key"
                  class="stat-item"
                  :class="{ 'stat-item-distribution': isDistributionKey(key) }"
                >
                  <div class="stat-label">{{ formatKey(key) }}</div>
                  <template v-if="isDistributionKey(key)">
                    <div v-if="isValidDistribution(value)" class="distribution-content">
                      <div
                        v-for="(count, label) in value"
                        :key="label"
                        class="distribution-item"
                      >
                        <span class="distribution-label">{{ formatDistributionLabel(key, label) }}：</span>
                        <span class="distribution-count">{{ formatValue(count) }}</span>
                      </div>
                    </div>
                    <el-alert
                      v-else
                      type="warning"
                      :closable="false"
                      show-icon
                      class="distribution-error"
                    >
                      <template #title>数据格式异常，请检查后端统计服务</template>
                      <template #default>
                        <div class="error-detail">{{ JSON.stringify(value) }}</div>
                      </template>
                    </el-alert>
                  </template>
                  <div v-else class="stat-value">{{ formatValue(value) }}</div>
                </div>
              </div>
            </div>

            <!-- 合规指标 -->
            <div v-if="showComplianceStats" class="stats-block">
              <h3 class="stats-title">合规指标</h3>
              <div class="stats-grid">
                <div
                  v-for="(value, key) in filteredComplianceData"
                  :key="key"
                  class="stat-item"
                  :class="{ 'stat-item-distribution': isDistributionKey(key) }"
                >
                  <div class="stat-label">{{ formatKey(key) }}</div>
                  <template v-if="isDistributionKey(key)">
                    <div v-if="isValidDistribution(value)" class="distribution-content">
                      <div
                        v-for="(count, label) in value"
                        :key="label"
                        class="distribution-item"
                      >
                        <span class="distribution-label">{{ formatDistributionLabel(key, label) }}：</span>
                        <span class="distribution-count">{{ formatValue(count) }}</span>
                      </div>
                    </div>
                    <el-alert
                      v-else
                      type="warning"
                      :closable="false"
                      show-icon
                      class="distribution-error"
                    >
                      <template #title>数据格式异常，请检查后端统计服务</template>
                      <template #default>
                        <div class="error-detail">{{ JSON.stringify(value) }}</div>
                      </template>
                    </el-alert>
                  </template>
                  <div v-else-if="isPercentageKey(key)" class="stat-percentage">
                    <span class="percentage-value">{{ formatPercentage(value) }}</span>
                    <span class="percentage-symbol">%</span>
                  </div>
                  <div v-else class="stat-value">{{ formatValue(value) }}</div>
                </div>
              </div>
            </div>

            <!-- 互动指标 -->
            <div v-if="showInteractionStats" class="stats-block">
              <h3 class="stats-title">互动指标</h3>
              <div class="stats-grid">
                <div
                  v-for="(value, key) in filteredInteractionData"
                  :key="key"
                  class="stat-item"
                >
                  <div class="stat-label">{{ formatKey(key) }}</div>
                  <div v-if="isPercentageKey(key)" class="stat-percentage">
                    <span class="percentage-value">{{ formatPercentage(value) }}</span>
                    <span class="percentage-symbol">%</span>
                  </div>
                  <div v-else class="stat-value">{{ formatValue(value) }}</div>
                </div>
              </div>
            </div>

            <el-empty
              v-if="!hasData"
              description="暂无统计数据"
              :image-size="100"
            />
          </el-card>
        </div>

        <div v-if="loading" class="loading-wrapper">
          <el-skeleton :rows="5" animated />
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { reactive, ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { fetchMainInfo, fetchStatsData } from '../src/api/enterprise.js'

const router = useRouter()
const userStore = useUserStore()

const defaultAvatar = 'https://avatars.githubusercontent.com/u/0?v=4'

const user = reactive({ name: '', avatar: '', position: '', phone: '', email: '' })
const showUserCard = ref(false)
const userAreaRef = ref(null)
const userCardRef = ref(null)
const loading = ref(false)
const statsData = ref(null)

const queryParams = reactive({
  period: 1,
  stats_date: '',
  stats_type: 0
})

const datePickerType = computed(() => 'date')
const dateFormat = computed(() => 'YYYY-MM-DD')

const hiddenDistributionMatchers = [
  '行业分布',
  'industry',
  '薪资段分布',
  'salary_range',
  '违规类型分布',
  'violation'
]

const filterMetrics = (source) => {
  if (!source || typeof source !== 'object') return {}
  return Object.fromEntries(
    Object.entries(source).filter(([key]) => {
      const lowerKey = String(key).toLowerCase()
      return !hiddenDistributionMatchers.some((matcher) =>
        lowerKey.includes(matcher.toLowerCase())
      )
    })
  )
}

const filteredBusinessData = computed(() =>
  filterMetrics(statsData.value?.data?.business)
)
const filteredComplianceData = computed(() =>
  filterMetrics(statsData.value?.data?.compliance)
)
const filteredInteractionData = computed(() =>
  filterMetrics(statsData.value?.data?.interaction)
)

const showBusinessStats = computed(() => {
  return (
    (queryParams.stats_type === 0 || queryParams.stats_type === 1) &&
    Object.keys(filteredBusinessData.value).length > 0
  )
})

const showComplianceStats = computed(() => {
  return (
    (queryParams.stats_type === 0 || queryParams.stats_type === 2) &&
    Object.keys(filteredComplianceData.value).length > 0
  )
})

const showInteractionStats = computed(() => {
  return (
    (queryParams.stats_type === 0 || queryParams.stats_type === 3) &&
    Object.keys(filteredInteractionData.value).length > 0
  )
})

const hasData = computed(() => {
  return (
    Object.keys(filteredBusinessData.value).length > 0 ||
    Object.keys(filteredComplianceData.value).length > 0 ||
    Object.keys(filteredInteractionData.value).length > 0
  )
})

onMounted(async () => {
  await loadMainInfo()
  document.addEventListener('click', handleGlobalClick, true)
  initDefaultDate()
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleGlobalClick, true)
})

function initDefaultDate() {
  const today = new Date()
  if (queryParams.period === 1) {
    queryParams.stats_date = formatDate(today)
  } else if (queryParams.period === 2) {
    queryParams.stats_date = formatDate(getSunday(today))
  } else {
    queryParams.stats_date = formatDate(getLastMonthEnd(today))
  }
}

function toggleUserCard() {
  const next = !showUserCard.value
  showUserCard.value = next
  if (next) {
    loadMainInfo()
  }
}

function handleGlobalClick(e) {
  const area = userAreaRef.value
  if (!area) return
  if (!area.contains(e.target)) {
    showUserCard.value = false
  }
}

function goAccount() {
  ElMessage.info('前往账号设置')
  showUserCard.value = false
}

function goSecurity() {
  ElMessage.info('前往安全设置')
  showUserCard.value = false
}

function logout() {
  try {
    if (userStore && typeof userStore.logout === 'function') {
      userStore.logout()
    }
  } catch (e) {}
  localStorage.removeItem('token')
  localStorage.removeItem('access')
  localStorage.removeItem('refresh')
  localStorage.removeItem('user')
  localStorage.removeItem('dingtalk_user_type')
  ElMessage.success('已退出登录')
  showUserCard.value = false
  router.replace('/login')
}

function handleMenuSelect(index) {
  const routeMap = {
    jobs: '/enterprise/main',
    stats: '/enterprise/stats'
  }

  if (routeMap[index]) {
    router.push(routeMap[index])
  } else {
    ElMessage.info('功能开发中，敬请期待')
  }
}

async function loadMainInfo() {
  try {
    const token = localStorage.getItem('token') || ''
    const data = await fetchMainInfo(token)
    if (data) {
      const info = data.user_info || {}
      user.name = info.name || ''
      user.avatar = info.avatar || ''
      user.position = info.position || ''
      user.phone = info.phone || ''
      user.email = info.email || ''
    }
  } catch (error) {
    ElMessage.error(error?.response?.data?.error || '加载用户信息失败')
  }
}

function handlePeriodChange() {
  initDefaultDate()
}

function handleDateChange(value) {
  if (!value) return
  if (queryParams.period === 2) {
    const sunday = getSunday(new Date(value))
    queryParams.stats_date = formatDate(sunday)
  } else if (queryParams.period === 3) {
    const monthEnd = getLastMonthEnd(new Date(value))
    queryParams.stats_date = formatDate(monthEnd)
  }
}

async function handleQuery() {
  if (!queryParams.stats_date) {
    ElMessage.warning('请选择统计日期')
    return
  }
  try {
    loading.value = true
    const token = localStorage.getItem('token') || ''
    const response = await fetchStatsData(
      {
        period: queryParams.period,
        stats_date: queryParams.stats_date,
        stats_type: queryParams.stats_type
      },
      token
    )
    if (response.code === 200) {
      statsData.value = response.data
    } else {
      ElMessage.error(response.msg || '查询失败')
    }
  } catch (error) {
    ElMessage.error(error?.response?.data?.error || '查询失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

function handleReset() {
  queryParams.period = 1
  queryParams.stats_type = 0
  initDefaultDate()
  statsData.value = null
}

function formatDate(date) {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

function getSunday(date) {
  const d = new Date(date)
  const day = d.getDay()
  const diff = d.getDate() - day + (day === 0 ? 0 : 7)
  return new Date(d.setDate(diff))
}

function getLastMonthEnd(date) {
  const d = new Date(date)
  return new Date(d.getFullYear(), d.getMonth() + 1, 0)
}

function formatKey(key) {
  if (/[\u4e00-\u9fa5]/.test(key)) return key
  return key
    .split('_')
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(' ')
}

function formatValue(value) {
  if (typeof value === 'number') {
    return value.toLocaleString()
  }
  if (typeof value === 'object' && value !== null) {
    if (Array.isArray(value)) {
      return value.join(', ')
    }
    return JSON.stringify(value)
  }
  return value
}

function isDistributionKey(key) {
  const matchers = [
    '行业分布',
    'industry',
    '薪资段分布',
    'salary_range',
    '违规类型分布',
    'violation'
  ]
  const lowercase = key.toLowerCase()
  return matchers.some((item) => lowercase.includes(item.toLowerCase()) || key.includes('分布'))
}

function isValidDistribution(value) {
  if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
  return Object.values(value).every((val) => typeof val === 'number')
}

function isPercentageKey(key) {
  const matchers = ['率', 'pass_rate', 'conversion', 'reply', '响应']
  const lowercase = key.toLowerCase()
  return matchers.some((item) => lowercase.includes(item.toLowerCase()))
}

function formatPercentage(value) {
  if (typeof value === 'number') {
    return value.toFixed(2)
  }
  return value
}

function formatDistributionLabel(distributionKey, label) {
  if (distributionKey.includes('industry') || distributionKey.includes('行业')) {
    return mapIndustryCode(label)
  }
  return label
}

function mapIndustryCode(code) {
  const map = {
    internet: '互联网',
    finance: '金融',
    education: '教育',
    healthcare: '医疗',
    manufacturing: '制造业',
    real_estate: '房地产',
    other: '其他'
  }
  return map[code] || code
}
</script>

<style scoped>
.layout {
  height: 100vh;
}
.topbar {
  display: flex;
  align-items: center;
  padding: 0 16px;
  background: #fff;
  border-bottom: 1px solid #eef0f3;
}
.brand {
  font-size: 18px;
  font-weight: 600;
}
.spacer {
  flex: 1;
}
.gray-text {
  color: #999;
  margin-right: 16px;
}
.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
  position: relative;
}
.user-name {
  color: #333;
  cursor: pointer;
  transition: color 0.2s;
}
.user-name.active {
  color: #00c293;
  font-weight: 600;
}
.user-card {
  position: absolute;
  top: 56px;
  right: 0;
  width: 240px;
  background: #fff;
  border: 1px solid #eef0f3;
  border-radius: 12px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  z-index: 1000;
}
.user-card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 16px;
  background: linear-gradient(90deg, #f6fffb 0%, #ffffff 100%);
}
.uc-head {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.uc-name {
  font-weight: 600;
  color: #333;
}
.uc-pos {
  font-size: 12px;
  color: #666;
}
.user-card-body {
  display: grid;
}
.uc-item {
  padding: 12px 16px;
  cursor: pointer;
  color: #333;
}
.uc-item:hover {
  background: #f7f9fb;
}
.user-card-footer {
  border-top: 1px solid #f0f2f5;
}
.uc-logout {
  padding: 12px 16px;
  color: #ff4d4f;
  cursor: pointer;
}
.uc-logout:hover {
  background: #fff1f0;
}
.sidebar {
  border-right: 1px solid #eef0f3;
}
.content {
  background: #fafbfc;
  padding: 20px;
}
.query-section {
  margin-bottom: 20px;
}
.query-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
}
.form-item {
  display: flex;
  align-items: center;
  gap: 12px;
}
.form-item label {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
}
.form-actions {
  display: flex;
  gap: 12px;
}
.stats-section {
  margin-top: 20px;
}
.stats-card {
  background: #fff;
}
.card-header {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}
.stats-block {
  margin-bottom: 32px;
}
.stats-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #00c293;
}
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;
}
.stat-item {
  padding: 16px;
  background: #f7f9fb;
  border-radius: 8px;
  border-left: 4px solid #00c293;
  transition: all 0.3s;
}
.stat-item:hover {
  background: #f0f5ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 194, 147, 0.1);
}
.stat-label {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
}
.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #00c293;
}
.stat-percentage {
  display: flex;
  align-items: baseline;
  gap: 4px;
}
.percentage-value {
  font-size: 24px;
  font-weight: 600;
  color: #00c293;
}
.percentage-symbol {
  font-size: 18px;
  color: #666;
}
.stat-item-distribution {
  grid-column: span 2;
}
.distribution-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 200px;
  overflow-y: auto;
}
.distribution-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 12px;
  background: #ffffff;
  border-radius: 6px;
  font-size: 13px;
}
.distribution-label {
  color: #666;
}
.distribution-count {
  color: #00c293;
  font-weight: 600;
}
.distribution-error {
  margin-top: 12px;
}
.error-detail {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  word-break: break-all;
}
.loading-wrapper {
  margin-top: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}
</style>

